package com.any.hook.core;

import com.any.hook.common.element.ColumnCast;
import com.any.hook.common.exception.ErrorCode;
import com.any.hook.common.exception.HookException;
import com.any.hook.common.util.Configuration;
import com.any.hook.core.job.JobContainer;
import com.any.hook.core.taskgroup.TaskGroupContainer;
import com.any.hook.core.util.ConfigParser;
import com.any.hook.core.util.ConfigurationValidate;
import com.any.hook.core.util.ExceptionTracker;
import com.any.hook.core.util.FrameworkErrorCode;
import com.any.hook.core.util.container.CoreConstant;
import com.any.hook.core.util.container.LoadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Engine {
    private static String RUNTIME_MODE;
    private static final Logger LOG= LoggerFactory.getLogger(Engine.class);

    public static void main(String[] args) throws Exception{
        String myargs="{\n" +
                "    \"job\": {\n" +
                "        \"setting\": {\n" +
                "            \"speed\": {\n" +
                "                 \"channel\": 3\n" +
                "            },\n" +
                "            \"errorLimit\": {\n" +
                "                \"record\": 0,\n" +
                "                \"percentage\": 0.02\n" +
                "            }\n" +
                "        },\n" +
                "        \"content\": [\n" +
                "            {\n" +
                "                \"reader\": {\n" +
                "                    \"name\": \"mysqlreader\",\n" +
                "                    \"parameter\": {\n" +
                "                        \"username\": \"root\",\n" +
                "                        \"password\": \"123456\",\n" +
                "                        \"column\": [\n" +
                "                            \"uuid\",\n" +
                "                            \"checkevent_id\", \n" +
                "                            \"username\",\n" +
                "                            \"password\",\n" +
                "                            \"sfzh\",\n" +
                "                            \"sbid\",\n" +
                "                            \"cphm\",\n" +
                "                            \"hpzl\",\n" +
                "                            \"check_id\",\n" +
                "                            \"check_name\",\n" +
                "                            \"gz\",\n" +
                "                            \"date\",\n" +
                "                            \"ldqy\",\n" +
                "                            \"ip\",\n" +
                "                            \"checkpoint_id\",\n" +
                "                            \"name\",\n" +
                "                            \"excuse\",\n" +
                "                            \"rank\",\n" +
                "                            \"sszdld\",\n" +
                "                            \"phone\",\n" +
                "                            \"black_remark\",\n" +
                "                            \"pcsj\",\n" +
                "                            \"create_time\",\n" +
                "                            \"is_upload\"\n" +
                "                        ],\n" +
                "                        \"splitPk\": \"uuid\",\n" +
                "                        \"connection\": [\n" +
                "                            {\n" +
                "                                \"table\": [\n" +
                "                                    \"tb_car_record\"\n" +
                "                                ],\n" +
                "                                \"jdbcUrl\": [\n" +
                "     \"jdbc:mysql://192.168.106.248:3306/infoveriplatform_test\"\n" +
                "                                ]\n" +
                "                            }\n" +
                "                        ]\n" +
                "                    }\n" +
                "                },\n" +
                "               \"writer\": {\n" +
                "                    \"name\": \"streamwriter\",\n" +
                "                    \"parameter\": {\n" +
                "                        \"print\":true\n" +
                "                    }\n" +
                "                }\n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "}";
        hookApi(myargs,-1L);
    }

    public static void hookApi(String myargs,Long jobid){
        int exitCode=0;
        try{
            Engine.entryDirect(myargs,jobid);
        }catch (Throwable e){
            exitCode=1;
            LOG.error("改任务最可能的错误原因是：\n"+ ExceptionTracker.trace(e));
            if(e instanceof HookException){
                HookException tempException=(HookException)e;
                ErrorCode errorCode=tempException.getErrorCode();
                if(errorCode instanceof FrameworkErrorCode){
                    FrameworkErrorCode tempErrorCode=(FrameworkErrorCode) errorCode;
                    exitCode=tempErrorCode.toExitValue();
                }
            }
            LOG.info(String.format("该任务%s返回码是：%s\n",jobid,exitCode));
        }
        LOG.info(String.format("该任务%s返回码是：%s\n",jobid,exitCode));
    }

    public static void entryDirect(final String jobConfig,final Long jobid) throws Throwable{
        long jobId=jobid;
        Configuration configuration = ConfigParser.parse(jobConfig);
        configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, jobId);
        LOG.debug(configuration.toJSON());
        ConfigurationValidate.doValidate(configuration);
        Engine engine = new Engine();
        engine.start(configuration);
    }
    /* check job model (job/task) first */
    public void start(Configuration allConf) {

        RUNTIME_MODE="standalone";
        // 绑定column转换信息
        ColumnCast.bind(allConf);
        /**
         * 初始化PluginLoader，可以获取各种插件配置
         */
        LoadUtil.bind(allConf);

        boolean isJob = !("taskGroup".equalsIgnoreCase(allConf
                .getString(CoreConstant.DATAX_CORE_CONTAINER_MODEL)));
        //JobContainer会在schedule后再行进行设置和调整值
        int channelNumber = 0;
        AbstractContainer container;
        long instanceId;
        int taskGroupId = -1;
        if (isJob) {
            allConf.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_MODE, RUNTIME_MODE);
            container = new JobContainer(allConf);
            instanceId = allConf.getLong(
                    CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, 0);

        } else {
            container = new TaskGroupContainer(allConf);
            instanceId = allConf.getLong(
                    CoreConstant.DATAX_CORE_CONTAINER_JOB_ID);
            taskGroupId = allConf.getInt(
                    CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_ID);
            channelNumber = allConf.getInt(
                    CoreConstant.DATAX_CORE_CONTAINER_TASKGROUP_CHANNEL);
        }

        int priority = 0;
        try {
            priority = Integer.parseInt(System.getenv("SKYNET_PRIORITY"));
        } catch (NumberFormatException e) {
            LOG.warn("prioriy set to 0, because NumberFormatException, the value is: " + System.getProperty("PROIORY"));
        }

        Configuration jobInfoConfig = allConf.getConfiguration(CoreConstant.DATAX_JOB_JOBINFO);

        container.start();
    }
}
